package com.bigfans.searchservice.service.impl;

import com.bigfans.framework.es.ElasticTemplate;
import com.bigfans.framework.es.request.CreateIndexCriteria;
import com.bigfans.framework.es.request.CreateMappingCriteria;
import com.bigfans.framework.es.schema.DefaultIndexSettingsBuilder;
import com.bigfans.searchservice.schema.mapping.CategoryMapping;
import com.bigfans.searchservice.service.CategoryIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service(CategoryIndexServiceImpl.BEAN_NAME)
public class CategoryIndexServiceImpl implements CategoryIndexService {

    public static final String BEAN_NAME = "categoryIndexService";

    @Autowired
    private ElasticTemplate elasticTemplate;

    public void create() throws Exception {
        this.createIndex();
        this.createMapping();
    }

    public void createIndex() throws Exception {
        elasticTemplate.deleteIndex(CategoryMapping.INDEX);
        if (!elasticTemplate.isIndexExists(CategoryMapping.INDEX)) {
            CreateIndexCriteria criteria = new CreateIndexCriteria();
            criteria.setIndexName(CategoryMapping.INDEX);
            criteria.setAlias(CategoryMapping.ALIAS);
            criteria.setVersion(1L);
            criteria.setSettingsBuilder(new DefaultIndexSettingsBuilder());
            elasticTemplate.createIndex(criteria);
        }
    }

    public void createMapping() throws Exception {
        CreateMappingCriteria action = new CreateMappingCriteria();
        action.setMappingBuilder(new CategoryMapping());
        action.setIndexName(CategoryMapping.INDEX);
        action.setType(CategoryMapping.TYPE);
        elasticTemplate.createMapping(action);
    }

}
